//
//  PartyVirtualTestController.m
//  UESTCPioneer
//
//  Created by Apple on 14-9-26.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyVirtualTestController.h"
#import "SSCheckBoxView.h"
#import "UIHelpers.h"
#import "MBProgressHUD.h"
#import "PartyVirtualTestEntity.h"
#import "PartyTestResultController.h"

@interface PartyVirtualTestController ()<UIAlertViewDelegate>
{
    UIScrollView * _scrollView;
    UIView * _answerView;
    UIButton * _resultBtn;
    UITextView * _answerTextView;
    UITextView * _questionTextView;
    UIButton * _rightBtn;
    UIButton * _errorBtn;
    UIView * _questionView;
    UIView * _choseView;
    UILabel * _titlelabel;
    MBProgressHUD * HUD;
    
    NSMutableArray * _dataArray;
    NSInteger _no;
    NSInteger _index;
    NSInteger _count;
    NSInteger _totalScore;
    
    NSInteger _singleScore;//单选答对数量
    NSInteger _mutilScore; //多选答对数量
    
    NSString * _answerText;
    NSDictionary * _typeDict;
    UIButton * _titleNoBtn;
    UILabel * _titleKind;
    BOOL _isSingle;
    
    NSMutableArray * _SSCheckBoxArray;
    BOOL _isReturn;
    NSMutableArray * _answerArray;
}
@end

@implementation PartyVirtualTestController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _no = 0;
    _scrollView.scrollEnabled = NO;
    _SSCheckBoxArray = [NSMutableArray array];
    //1.设置问题View
    [self setQuestionView];
    //2.设置解析View
    [self setAnswerView];
    
    _answerView.hidden = YES;
    self.title = @"党课模考";
    
    [self addChooseButton];
    
    _typeDict = @{@"type":@"getSingle"};
    //    _titleKind.text = @"[单选题]";
    [_titleKind setTextColor:[UIColor redColor]];
    _isSingle = YES;
    _isReturn = NO;
    
    _answerArray = [NSMutableArray array];
    
    [self getServerData];
    
}

-(void)viewWillAppear:(BOOL)animated{
    _no = 0;
    _index = 0;
    _singleScore = 0;
    _mutilScore = 0;
    _isSingle = YES;
    
    _totalScore = 0;
    _singleScore = 0;
    _mutilScore = 0;
    if (_isReturn ) {
        [_dataArray removeAllObjects];
        _typeDict = @{@"type":@"getSingle"};
        //        _titleKind.text = @"[单选题]";
        [self resetSSCheckBoxView];
        [self getServerData];
    }
}

-(void)getServerData{
    //显示指示器
    MBProgressHUD * hud  = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    hud.labelText = @"考题加载中...";
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.dimBackground = YES;
    
    [NetworkCenter RKRequestWithData:_typeDict EntityName:@"PartyVirtualTestEntity" Mapping:[Mapping PartyVirtualTestEntityMapping] SuccessBlock:^(NSArray *resultArray) {
        
        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        [newArray addObjectsFromArray:_dataArray];
        [newArray addObjectsFromArray:resultArray];
        //        NSArray *result = [[NSArray alloc]initWithArray:newArray];
        _dataArray=newArray;
        
        _count = resultArray.count;
        _index = 0;
        if (resultArray.count == 0) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络较差，考题加载失败，是否重新加载?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            
            [alert show];
        }
        
        [self setQuestionText];
        //清除指示器
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
    } failure:^(NSError *error) {
        
        
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络较差，考题加载失败，是否重新加载?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        
        [alert show];
        //清除指示器
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //清除指示器
    [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
}

-(void)addChooseButton{
    
    //添加选择按钮
    NSMutableArray *a = [[NSMutableArray alloc] initWithCapacity:4];
    self.checkboxes = a;
    
    NSArray * textArray = @[@"A",@"B",@"C",@"D"];
    CGFloat addtion = (self.view.frame.size.width - 54*4 -40)/3;
    
    SSCheckBoxView *cbv = nil;
    CGRect frame ;
    for (int i = 0; i < 4; i++) {
        
        frame = CGRectMake(10+i*(addtion+54), 10, 54, 45);
        cbv = [[SSCheckBoxView alloc] initWithFrame:frame
                                              style:kSSCheckBoxViewStyleCycle
                                            checked:NO];
        
        [cbv setStateChangedTarget:self
                          selector:@selector(checkBoxViewChangedState:)];
        cbv.tag = i;
        [cbv setText:textArray[i]];
        [_choseView addSubview:cbv];
        [self.checkboxes addObject:cbv];
//        frame.origin.y += 36;
    }
}

-(void)setQuestionView{
    
    CGFloat w = self.view.frame.size.width;
    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    scrollView.contentSize = CGSizeMake(w, 650);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor colorWithRed:232.0f/255.0f green:233.0f/255.0f blue:232.0f/255.0f alpha:1];
    _scrollView = scrollView;
    
    _scrollView.scrollEnabled = NO;
    
    
    //1.设置UI
    UIView * questionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, 400)];
    [scrollView addSubview:questionView];
    _questionView = questionView;
    
    CGFloat x = (w - 150) / 2;
    
    //    //1.0 关于题型数量的说明
    //    UILabel * titlelabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    //    [titlelabel setTextColor:[UIColor redColor]];
    //    [titlelabel setFont:[UIFont systemFontOfSize:15.0f]];
    //    [_questionView addSubview:titlelabel];
    //    _titlelabel = titlelabel;
    
    //1.1 题号
    UIButton * titleNoBtn = [[UIButton alloc] initWithFrame:CGRectMake(x - 5, 10, 150, 40)];
    [titleNoBtn setTitleEdgeInsets:UIEdgeInsetsMake(22, 5, 0, 0)];
    titleNoBtn.contentMode = UIViewContentModeScaleAspectFit;
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateNormal];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateHighlighted];
    
    [titleNoBtn.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    [questionView addSubview:titleNoBtn];
    [self.view addSubview:scrollView];
    _titleNoBtn = titleNoBtn;
    
    //1.2 题目
    CGFloat y = CGRectGetMaxY(titleNoBtn.frame);
    UITextView * questionTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, y , w - 20, 230)];
    [questionTextView setEditable:NO];
    
    [questionTextView setTextContainerInset:UIEdgeInsetsMake(10, 0, 0, 0)];
    
    questionTextView.font = [UIFont systemFontOfSize:16.0f];
    _questionTextView = questionTextView;
    
    [questionView addSubview:questionTextView];
    
    /*改动优化后，去掉 2014-10-09
     CGFloat lX = (questionTextView.frame.size.width - 80) / 2;
     UILabel * titleKind = [[UILabel alloc] initWithFrame:CGRectMake(lX, 0, 80, 40)];
     [questionTextView addSubview:titleKind];
     _titleKind = titleKind;
     */
    CGFloat btnY = CGRectGetMaxY(questionTextView.frame);
    
    //1.3 选择按钮
    //1.3.1添加独立父view
    UIView * backView = [[UIView alloc] initWithFrame:CGRectMake(10, btnY,self.view.frame.size.width - 20 , 100)];
    [_questionView addSubview:backView];
    _choseView= backView;
    
    //1.3.2添加确认按钮
    CGFloat btnX = (w - 20 - 180)/2;
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX,60,180, 30)];
    [rightBtn.layer setCornerRadius:5];
    [rightBtn.layer setBorderWidth:1];
    [rightBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateNormal];
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateHighlighted];
    [rightBtn setBackgroundColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f]];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [rightBtn setTitle:@"确认" forState:UIControlStateNormal];
    [rightBtn setTitle:@"确认" forState:UIControlStateHighlighted];
    rightBtn.tag = 0;
    [rightBtn addTarget:self action:@selector(returnResult:) forControlEvents:UIControlEventTouchUpInside];
    [_choseView addSubview:rightBtn];
    _rightBtn = rightBtn;
    [_rightBtn.layer setCornerRadius:5];
    
    
    CGFloat labelX = (questionTextView.frame.size.width - 59);
    CGFloat labelY = (questionTextView.frame.size.height - 49);
    //1.4 result标志
    UIButton * resultLbl = [[UIButton alloc] initWithFrame:CGRectMake(labelX, labelY, 45, 45)];
    
    [questionTextView addSubview:resultLbl];
    _resultBtn = resultLbl;
    
}

-(void)setAnswerView{
    
    CGFloat w = self.view.frame.size.width;
    //1.设置UI
    UIView * answerView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, w, 250)];
    [_scrollView addSubview:answerView];
    _answerView = answerView;
    
    CGFloat x = (w - 150) / 2;
    
    //1.1 题号
    UIButton * titleNoBtn = [[UIButton alloc] initWithFrame:CGRectMake(x - 5, 10, 150, 40)];
    titleNoBtn.contentMode = UIViewContentModeScaleAspectFit;
    [titleNoBtn setTitleEdgeInsets:UIEdgeInsetsMake(22, 5, 0, 0)];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateNormal];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateHighlighted];
    [titleNoBtn setTitle:@"答案" forState:UIControlStateNormal];
    [titleNoBtn.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    [answerView addSubview:titleNoBtn];
    [self.view addSubview:_scrollView];
    
    //1.2 答案
    CGFloat y = CGRectGetMaxY(titleNoBtn.frame);
    UITextView * answerTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, y , w - 20, 50)];
    [answerTextView setEditable:NO];
    answerTextView.font = [UIFont systemFontOfSize:16.0f];
    [answerView addSubview:answerTextView];
    answerTextView.textContainerInset = UIEdgeInsetsMake(13, 0, 0, 0);
    _answerTextView = answerTextView;
    
    //1.3 Next按钮
    CGFloat btnY = CGRectGetMaxY(answerTextView.frame) + 25;
    CGFloat btnX = (self.view.frame.size.width - 180)/2;
    UIButton * nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, 180, 30)];
    [nextBtn addTarget:self action:@selector(nextQuestion:) forControlEvents:UIControlEventTouchUpInside];
//    [nextBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateNormal];
//    [nextBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateHighlighted];
    [nextBtn setBackgroundColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f]];
    [nextBtn setTitle:@"下一题" forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一题" forState:UIControlStateHighlighted];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    
    [nextBtn.layer setBorderWidth:1];
    [nextBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    [nextBtn.layer setCornerRadius:5];
    [answerView addSubview:nextBtn];
    [nextBtn.layer setCornerRadius:5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)returnResult:(UIButton *)btn{
    
    if (_dataArray.count == 0) {
        [Alert showAlert:@"网络连接失败!"];
        return;
    }
    _scrollView.scrollEnabled = YES;
    if (!_isSingle) {
        [self setMutilAnswer];
    }
    
    if (_answerText == nil || [_answerText isEqualToString:@""]) {
        [Alert showAlert:@"请选择答案!"];
        return;
    }
    
    _choseView.hidden = YES;
    _resultBtn.hidden = NO;
    _scrollView.scrollEnabled = YES;
    _answerView.hidden = NO;
    CGFloat pointY = 0;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    if ( screenHeight < 500.0f) {
        pointY = 100;
    } else if (screenHeight < 550.0f){
        pointY = 30;
    }
    
    [UIView beginAnimations:@"Curl"context:nil];//动画开始
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_scrollView setContentOffset:CGPointMake(0, pointY)];
    [UIView commitAnimations];
    
    //计算结果
    [self calculateTotalScore];
}

-(void)nextQuestion:(UIButton*)btn{
    
    [UIView beginAnimations:@"Curl"context:nil];//动画开始
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [_scrollView setContentOffset:CGPointMake(0, 0)];
    _scrollView.scrollEnabled = NO;
    [UIView commitAnimations];
    
    if (_dataArray.count - 1 == _no && [_typeDict[@"type"] isEqualToString:@"getSingle"]) {
        [self setBeforeNext];
        _isSingle = NO;
        _titleKind.text = @"[多选题]";
        _typeDict = @{@"type":@"getMutil"};
        _no ++;
        //还原选项
        [self resetSSCheckBoxView];
        //请求网络数据
        [self getServerData];
    } else  if (_dataArray.count - 1 == _no && [_typeDict[@"type"] isEqualToString:@"getMutil"]){
        //答题结束,计算成绩
        [self sendAndShowResult];
    }else {
        _no++;
        _index ++;
        [self setBeforeNext];
        [self setQuestionText];
        [self resetSSCheckBoxView];
    }
}

-(void)setBeforeNext{
    _scrollView.scrollEnabled = NO;
    _choseView.hidden = NO;
    _answerView.hidden = YES;
    _resultBtn.hidden = YES;
    _answerText = @"";
}
#pragma mark 设置题目和解析
-(void)setQuestionText{
    _questionTextView.text = @"";
    PartyVirtualTestEntity * entity = _dataArray[_no];
    
    //设置题目
    _questionTextView.text = entity.content;
    //设置解析
    _answerTextView.text = [NSString stringWithFormat:@"答案:  %@",entity.answer];
    
    //设置题号
    NSString * type = _typeDict[@"type"];
    if ([type isEqualToString:@"getSingle"]) {
        [_titleNoBtn setTitle:[NSString stringWithFormat:@"单选题 [%i/%i]",_index+1,_count] forState:UIControlStateNormal] ;
        [_titleNoBtn setTitle:[NSString stringWithFormat:@"单选题 [%i/%i]",_index+1,_count] forState:UIControlStateHighlighted] ;
    } else if ([type isEqualToString:@"getMutil" ]) {
        [_titleNoBtn setTitle:[NSString stringWithFormat:@"多选题 [%i/%i]",_index+1,_count] forState:UIControlStateNormal] ;
        [_titleNoBtn setTitle:[NSString stringWithFormat:@"多选题 [%i/%i]",_index+1,_count] forState:UIControlStateHighlighted] ;
    }
    
}

-(void)calculateTotalScore{
    PartyVirtualTestEntity * entity = _dataArray[_no];
    NSLog(@"_answerText = %@,entity.answer = %@",_answerText,entity.answer);
    
    if ([_answerText isEqualToString:entity.answer]) {
        _totalScore++;
        
        if (_isSingle) {
            _singleScore ++;
        } else {
            _mutilScore ++;
        }
        
        [_resultBtn setImage:[UIImage imageNamed:@"yes.png"] forState:UIControlStateNormal];
    } else {
        [_resultBtn setImage:[UIImage imageNamed:@"no.png"] forState:UIControlStateNormal];
    }
}

-(void)setMutilAnswer{
    _answerText = @"";
    for (NSString * str in _answerArray) {
        _answerText = [_answerText stringByAppendingString:str];
    }
    [_answerArray removeAllObjects];
    NSLog(@"_answerText = %@",_answerText);
}

-(void)checkBoxViewChangedState:(SSCheckBoxView *)cbv{
    
    if (_isSingle) {
        //如果是单选
        [self resetSSCheckBoxView];
        cbv.checked = YES;
        _answerText = cbv.textLabel.text;
    } else {
        //如果是多选
        NSUInteger index = [_answerArray indexOfObject:cbv.textLabel.text];
        if (NSNotFound == index) {
            [_answerArray addObject:cbv.textLabel.text];
        } else {
            [_answerArray removeObjectAtIndex:index];
        }
    }
    
    NSLog(@"客官您翻了%@的牌子!",_answerText);
}

-(void)resetSSCheckBoxView{
    for (int i = 0; i < self.checkboxes.count; i++) {
        SSCheckBoxView *cbv = self.checkboxes[i];
        cbv.checked = NO;
    }
}

#pragma mark - 计算并显示成绩
-(void)sendAndShowResult{
    _isReturn = YES;
    //1.向后台发送成绩
    //显示指示器
    MBProgressHUD * hud  = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    hud.labelText = @"请稍后,成绩上传中...";
    hud.dimBackground = YES;
    NSDictionary *requestData=@{@"type":@"uploadScore"
                                ,@"userId":[constant getUserId]
                                ,@"singlescore":[NSString stringWithFormat:@"%i",_singleScore]
                                ,@"mutilscore":[NSString stringWithFormat:@"%i",_mutilScore]};
    NSLog(@"_singleScore = %i,_mutilScore = %i",_singleScore,_mutilScore);
    NSLog(@"requestData = %@",requestData);
    [NetworkCenter AFRequestWithData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic =arr[0];
        NSLog(@"返回值dic = %@",dic);
        if ([dic[@"result"] isEqualToString:@"success"]){
            
            //设置相应地属性
            [self setBeforeNext];
            
            //2.显示成绩
            NSString * name = [NSString stringWithFormat:@"%@同志:",[constant getName] ];
            NSString * text = [NSString stringWithFormat:@"     在本次党课模考中答对%i道单选题,%i道多选题,获得%@积分.",_singleScore,_mutilScore,dic[@"cause"]];
            PartyTestResultController * controller = [[PartyTestResultController alloc] initWithName:name result:text integral:dic[@"cause"]];
            
            [self.navigationController pushViewController:controller animated:YES];
            
            //清除指示器
            [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        } else {
            //清除指示器
            [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
            [Alert showAlert:@"上传失败"];
        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        //        NSLog(@"operation.responseString = %@",operation.responseString);
        [Alert showAlert:@"网络连接出错"];
        NSLog(@"网络连接出错 = %@",error.localizedDescription);
        //清除指示器
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
    }];
}

#pragma mark UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        [self getServerData];
    } else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
@end
